<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2018/11/26
 * Time: 20:31
 */

namespace app\storage\model;

use think\Db;
use think\Model;


class ShelvesModel extends Model
{
    protected $table = 'iwh_shelves';
    protected $pk = 'uuid';

    public function SeatModel()
    {
        return $this->hasMany('SeatModel', 'shelves_uuid', 'uuid');
    }

    public function Storage()
    {
        return $this->belongsTo('StorageModel', 'storage_uuid', 'uuid')->bind('name');
    }


    public function getShelf($condition)
    {
        $where = $condition['where'];
        $pageIndex = $condition['pageIndex'];
        $pageSize = $condition['pageSize'];
        if (empty($where['name'])) {
            $hasWhere = [];
        } else {
            $hasWhere['name'] = $where['name'];
            unset($where['name']);
        }
        $ret['total'] = $this->hasWhere('Storage', $hasWhere)->where($where)->with('Storage')->count();
        $ret['row'] = $this->hasWhere('Storage', $hasWhere)
            ->order('storage_uuid asc,shelves_code asc')
            ->where($where)->with('Storage')
            ->page($pageIndex, $pageSize)
            ->select();

        return $ret;
    }

    /**模型关联没有事务处理，事务处理使用db
     * @param $uuid
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function deleteShelf($uuid)
    {
        Db::startTrans();
        $shelfTran = Db::table('iwh_shelves')->where(['uuid' => $uuid])->delete();
        $seatTran = Db::table('iwh_seat')->where(['shelves_uuid' => $uuid])->delete();
        if ($shelfTran == true && $seatTran !== false) {
            Db::commit();
            return true;
        } else {
            Db::rollback();
            return false;
        }
    }
}

